package com.cacf.uddi.core;

import inspireit.uddi.BusinessEntity;
import inspireit.uddi.base.BusinessKey;
import inspireit.uddi.base.Name;
import inspireit.uddi.base.UDDIException;
import inspireit.uddi.collections.BusinessEntitys;
import inspireit.uddi.collections.Names;
import inspireit.uddi.collections.Results;
import inspireit.uddi.net.RemoteException;
import inspireit.uddi.request.UDDIProfile;
import inspireit.uddi.request.UDDIPublisher;
import inspireit.uddi.response.BusinessDetail;
import inspireit.uddi.response.DispositionReport;
import inspireit.uddi.response.base.Result;

public class SaveBusiness {

	public SaveBusiness(String nameBusiness, UDDIProfile uddiProfile)
			throws RemoteException {

		System.setProperty("java.protocol.handler.pkgs",
				"com.sun.net.ssl.internal.www.protocol");
		java.security.Security
				.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		try {
			// get an appropriate publisher
			UDDIPublisher publisher = UDDIPublisher.getPublisher(uddiProfile);

			// build up the BusinessEntity to save in the registry
			Name name = new Name(nameBusiness);
			BusinessKey businessKey = null; // it's a new business...
			BusinessEntity businessEntity = new BusinessEntity(businessKey,
					name);

			// execute the SaveBusiness operation and get back the
			// BusinessDetail
			BusinessDetail businessDetail = publisher.saveBusiness(businessEntity);
			displaySavedBusinessEntity(businessDetail);

		} catch (UDDIException e) {
			System.out
					.println("An error has occured. More information follows.");
			DispositionReport dispositionReport = e.getDispositionReport();

			if (dispositionReport != null) {
				Results results = dispositionReport.getResults();
				Result result[] = results.toArray();

				for (int i = 0; i < result.length; i++) {
					System.out.println("Errno   : " + result[i].getErrNo()
							+ "\n KeyType : " + result[i].getKeyType()
							+ "\n ErrInfo : " + result[i].getErrInfo());
				}
			} else {
				System.out.println(e.getMessage());
			}
		}

	}

	private void displaySavedBusinessEntity(BusinessDetail businessDetail) {
		// get the saved BusinessEntity
		BusinessEntitys businessEntities = businessDetail.getBusinessEntitys();
		BusinessEntity savedBusinessEntity = (businessEntities.toArray())[0];

		System.out.println("BusinessEntity saved with business key : "
				+ savedBusinessEntity.getBusinessKey());
		System.out.println("BusinessEntity saved with name : "
				+ (savedBusinessEntity.getNames().toArray())[0]);
	}
}
